package com.bawei.module_apps.net

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.library_common.utils.LoggerUtils
import com.bawei.library_mvi.ui.BaseMviActivity
import com.bawei.module_apps.R
import com.bawei.module_apps.databinding.AppsActivityNetAppBinding
import com.bawei.module_apps.net.entity.RequestEntity
import com.bw.apps.net.entity.AppMultipleEntity
import com.bw.apps.net.entity.NetAppEntity
import com.bw.quickadapter.BaseQuickMultipleAdapter
import com.bw.widget.dialog.DownLoadDialog
import io.virtualapp.hook_sdk.app.InstallAppUtils
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.File
@Route(path = "/apps/net")
class NetAppActivity : BaseMviActivity<AppsActivityNetAppBinding>() {
    private lateinit var viewModel:NetAppViewModel
    private lateinit var  adapter:NetAppsAdapter
    private val installAppUtils : InstallAppUtils by lazy {InstallAppUtils() }
    private val apkPath : String by lazy {
        getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!.absolutePath
    }
    private lateinit var path:String
    private var dialog : DownLoadDialog ?=null
    //处理结果
    override fun handleState() {
        lifecycleScope.launch{
           viewModel.states.collect{
               when(it){
                   is NetAppState.SucceedState ->{
                       val list = it.list
                       adapter.setNewInstance(list)//刷新数据源
                   }
                   is NetAppState.Init ->{}
                   is NetAppState.ErrorState ->{
                       showMsg("失败")
                   }


                   is NetAppState.Start ->{//开始
                       dialog = DownLoadDialog(this@NetAppActivity)
                       dialog!!.let {
                           it.maxPrg = 100
                           it.titleStr = "测试下载"
                           it.show() }
                   }

                   is NetAppState.Progress ->{//下载中
                       val progress : NetAppState.Progress = it
                       dialog!!.setPrgNum(progress.progress)
                   }
                   is NetAppState.Err ->{//下载失败
                       showMsg("下载失败")

                   }
                   is NetAppState.Done ->{//下载完成：关闭对话框 安装app到虚拟机
                       dialog!!.dismiss()
                       if(!File(apkPath).exists()){
                           showMsg("下载失败")
                           return@collect
                       }
                       //在虚拟机中安装apk的过程
                       val flag = installAppUtils.installApp(path)
                       LoggerUtils.e("install","安装结果 $flag")
                       if (flag) {
                           showMsg("安装成功")
                       }
                       else
                           showMsg("安装失败")
                   }




               }
           }
        }

    }



    override fun initView() {
        super.initView()


        viewDataBinding.netAppsBar.backImg.setOnClickListener { finish() }
        viewDataBinding.netAppsBar.titleTv.text = "应用市场"
        adapter = NetAppsAdapter()
        val manager = GridLayoutManager(this,3)
        manager.orientation = GridLayoutManager.VERTICAL
        viewDataBinding.netAppsRv.layoutManager = manager
        //注意！！！！ 适配器最后设置
        viewDataBinding.netAppsRv.adapter = adapter
        viewDataBinding.netAppsRv.setHasFixedSize(true)
        //item的点击:viewmodel发送intent下载apk请求
        adapter.setOnItemCLickListener(object :BaseQuickMultipleAdapter.OnItemCLickListener{
            override fun onItemClick(adapter: RecyclerView.Adapter<*>?, position: Int) {
                lifecycleScope.launch{
                    val netAppsAdapter : NetAppsAdapter = adapter as NetAppsAdapter
                    path = apkPath+"/"+netAppsAdapter.data.get(position).appName+".apk" //下载路径
                    val apkUrl = netAppsAdapter.data.get(position).apkUrl//网络路径

                    viewModel.intents.send(NetAppIntent.NetAppDownloadIntent(apkUrl, File(path)))
                }
            }

        })

    }

    override fun getLayout(): Int {
        return  R.layout.apps_activity_net_app
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch{
            viewModel.intents.send(NetAppIntent.NetAppDataIntent(RequestEntity(1,1)))
        }
    }

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this).get(NetAppViewModel::class.java)

    }

}